package com.jy.appmarket.screenlock;

import com.jy.appmarket.AppMarketApplication;
import com.jy.appmarket.R;
import com.jy.appmarket.screenlock.activity.LockscreenShowActivity;
import com.jy.appmarket.screenlock.activity.TBLockScreenActivity;
import com.jy.appmarket.screenlock.prefs.LockPrefs;
import com.jy.appmarket.screenlock.service.LockerService;
import com.jy.appmarket.screenlock.utils.BaseInfoHelper;
import com.jy.appmarket.screenlock.utils.XiaomiUtils;
import com.jy.appmarket.utils.LogUtil;

import android.annotation.TargetApi;
import android.app.KeyguardManager;
import android.app.KeyguardManager.KeyguardLock;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.Toast;

public class LockScreenManager {
	protected static final String TAG = "LockScreenManager";
	private static LockScreenManager sInstance = null;

	private View mLockView;
	private WindowManager mWinManager = null;
	private boolean mIsLocked = false;
	private KeyguardLock mKeyguard;
	private Context mContext;
	private WindowManager.LayoutParams mWinParams;
	private ILockScreenListener mLockListener = null;
	private ILockScreenActivityListener mLockActivityListener = null;
	private MainLockViewManager mMainLockManager;
	private Runnable mUnLockRunnable = null;
	private static Handler mHandler = new Handler(Looper.getMainLooper());

	public interface ILockScreenListener {
		void onLock();

		void onUnLock();

		void onInitDefaultImage();
	}

	public interface ILockScreenActivityListener {
		void onChangeWallpaper();
	}

	/**
	 * 展示模式 true 展示activity false 展示悬浮窗(默认选项)
	 */
	private boolean mIsShowMode = false;

	public boolean isShowMode() {
		return mIsShowMode;
	}

	public void setOnLockScreenListener(ILockScreenListener listener) {
		mLockListener = listener;
	}

	public void setOnLockScreenActivityListener(ILockScreenActivityListener listener) {
		mLockActivityListener = listener;
	}

	private LockScreenManager(Context context) {
		mContext = context.getApplicationContext();
		mWinManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
		KeyguardManager keyguard = (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);
		mKeyguard = keyguard.newKeyguardLock(mContext.getPackageName());
		disableSystemLock();
	}

	public void disableSystemLock() {
		mKeyguard.disableKeyguard();
	}

	public void enableSystemLock() {
		mKeyguard.reenableKeyguard();
	}

	public static LockScreenManager getInstance(Context context) {
		if (sInstance == null) {
			synchronized (LockScreenManager.class) {
				if (sInstance == null) {
					sInstance = new LockScreenManager(context);
				}
			}
		}
		return sInstance;
	}

	private boolean mIsNeedNotice = false;

	@TargetApi(Build.VERSION_CODES.KITKAT)
	public void lock() {
		if (XiaomiUtils.isMIUI(mContext)) {
			mIsShowMode = !XiaomiUtils.isFloatWindowOpAllowed(mContext);
		}

		if (LockerService.isCalling()) {
			return;
		}
		if (mIsShowMode) {
			if (mLockActivityListener != null) {
				mLockActivityListener.onChangeWallpaper();
			}
		} else {
			if (mMainLockManager != null) {
				mMainLockManager.changeWallpaper();
				mMainLockManager.openSliding(false);
			}
		}
		if (mIsLocked) {
			return;
		}
		AppMarketApplication.sIsPauseLocked = false;
		mIsLocked = true;
		boolean lockScreenVoice = LockPrefs.isLockSoundOpen(mContext);
		if (lockScreenVoice) {
			LockSoundManager.play(mContext, LockSoundManager.SOUND_ID_LOCK);
		}
		if (mIsShowMode) {
			LogUtil.d(TAG, "start show activity");
			Intent intent = new Intent(mContext, LockscreenShowActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			mContext.startActivity(intent);
			return;
		}

		if (mWinParams == null) {
			mWinParams = new WindowManager.LayoutParams();
			if (mIsNeedNotice) {
				mWinParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
			} else {
				mWinParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;
			}

			mWinParams.flags = LayoutParams.FLAG_NOT_FOCUSABLE | LayoutParams.FLAG_DISMISS_KEYGUARD
					| LayoutParams.FLAG_SHOW_WHEN_LOCKED | LayoutParams.FLAG_LAYOUT_IN_SCREEN
					| LayoutParams.FLAG_HARDWARE_ACCELERATED | LayoutParams.FLAG_LAYOUT_NO_LIMITS;

			if (!mIsNeedNotice) {
				mWinParams.flags |= LayoutParams.FLAG_FULLSCREEN;
			}
			if (Build.VERSION.SDK_INT >= 19) {
				mWinParams.flags |= LayoutParams.FLAG_TRANSLUCENT_STATUS;
				mWinParams.flags |= LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
			}
			mWinParams.width = WindowManager.LayoutParams.MATCH_PARENT;

			final Display display = mWinManager.getDefaultDisplay();
			mWinParams.height = BaseInfoHelper.getRealHeight(display);

			mWinParams.x = 0;
			mWinParams.y = 0;
			mWinParams.format = PixelFormat.TRANSPARENT;
			// params.format=PixelFormat.RGBA_8888;
			mWinParams.windowAnimations = R.style.anim_locker_window;
			mWinParams.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN;
			mWinParams.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
			mWinParams.gravity = Gravity.TOP | Gravity.START;
		}
		initLockScreenViews();
		try {
			// 友盟日志显示三星手机会抛异常，下removeView同理
			mWinManager.addView(mLockView, mWinParams);
			startFakeActivity();
			notifyLocked();
		} catch (Exception e) {
			Toast.makeText(mContext, "由于系统限制，锁屏失败！", Toast.LENGTH_SHORT).show();
			LogUtil.e(TAG, "lock failed", e);
		}
	}

	private void initLockScreenViews() {
		mMainLockManager = new MainLockViewManager(mContext, false);
		mLockView = mMainLockManager.getMainLockView();
	}

	public void setWindowAnimations(int anim) {
		mWinParams.windowAnimations = anim;
		mWinManager.updateViewLayout(mLockView, mWinParams);
	}

	private void startFakeActivity() {
		Intent intent = new Intent(mContext, TBLockScreenActivity.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		mContext.startActivity(intent);
	}

	private void notifyLocked() {
		if (mLockListener != null) {
			mLockListener.onLock();
		}
	}

	/**
	 * 设置当调用unlock解锁后要执行的动作，解锁后，自动置为null
	 * 
	 * @param runnable
	 */
	public void setRunnableAfterUnLock(Runnable runnable) {
		mUnLockRunnable = runnable;
	}

	/**
	 * 调用会解锁，如果开启安全锁，会跳转到安全锁界面；如果希望在解锁后执行其它动作，请在调用unLock()
	 * 之前使用setRunnaleAfterUnLock()方法设置
	 * 默认会关闭背后的假Activity，如果不希望关闭这个Activity，可以使用unLock(boolean
	 * isCloseFakeActivity)方法
	 */
	public void unLock() {
		unLock(false);
	}

	/**
	 * 解锁
	 * 
	 * @param forceClose
	 *            如果为true，则忽略密码锁，直接解锁，比如来电话时
	 */
	public void unLock(boolean forceClose) {
		internalUnLock(forceClose);
	}

	private void internalUnLock(boolean forceClose) {

		if (!mIsLocked) {
			notifyUnLocked();
			return;
		}

		notifyUnLocked();

		if (mIsShowMode) {
			mContext.sendBroadcast(new Intent(LockscreenShowActivity.ACTION_FINISH_SHOW));
		} else {

			if (mMainLockManager != null) {
				mMainLockManager.unregisterReceiver();
				mMainLockManager.releaseCamera();
				if (!forceClose) {
					mMainLockManager.ClearMessageView();
				}
			}
			try {
				if (mUnLockRunnable != null) {
					mWinManager.removeView(mLockView);
				} else {
					mWinManager.removeViewImmediate(mLockView);
				}
			} catch (Exception e) {
				LogUtil.e(TAG, "unlock failed", e);
			}
			mLockView = null;
		}
		mIsLocked = false;
		if (mUnLockRunnable != null) {
			mHandler.post(mUnLockRunnable);
			mUnLockRunnable = null;
		}
		System.gc();
		System.runFinalization();
	}

	private void notifyUnLocked() {
		if (mLockListener != null) {
			mLockListener.onUnLock();
		}
	}

	public boolean isLocked() {
		return mIsLocked;
	}

}
